package com.yuexunit.mobilenurse.module.HospitalInfo.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Cost.adapter.CostListAdapter;
import com.yuexunit.mobilenurse.module.Cost.bean.CostDetail_Patfeelist;
import com.yuexunit.mobilenurse.module.Cost.model.impl.CostModel;
import com.yuexunit.mobilenurse.module.Cost.presenter.ICostPresenter;
import com.yuexunit.mobilenurse.module.Cost.presenter.impl.CostPresenter;
import com.yuexunit.mobilenurse.module.Cost.ui.Act_Cost;
import com.yuexunit.mobilenurse.module.Cost.ui.view.ICostView;
import com.yuexunit.mobilenurse.module.HospitalInfo.Act_HospitalInfo;
import com.yuexunit.mobilenurse.util.CreateJson;
import com.yuexunit.mobilenurse.util.ProUtil;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/7/13.
 */
public class Frag_Cost extends Fragment implements ICostView{

    @Bind(R.id.cost_list)
    public ListView cost_list;
    @Bind(R.id.cost_data)
    public TextView cost_data;
    @Bind(R.id.cost_todaycost)
    public TextView cost_todaycost;
    @Bind(R.id.cost_totalcost)
    public TextView cost_totalcost;
    @Bind(R.id.cost_prepaid)
    public TextView cost_prepaid;
    @Bind(R.id.cost_cost)
    public TextView cost_cost;

    private BaseAdapter adapter;
    SimpleDateFormat formatter;
    Calendar calendar = Calendar.getInstance();

    //距离当日天数
    private int countday = 0;
    public static final int INCREASE_COST_DAY = 1;
    public static final int DECREASE_COST_DAY = -1;
    public static final int SHOW_DIALOG = 1;
    public static final int DISMISS_DIALOG = -1;
    //病人住院号
    private String Visitno;
    //记录Log
    private final Logger log = LoggerFactory.getLogger(Act_Cost.class);
    LoadingDialog dialog;
    ICostPresenter presenter;

    ArrayList<CostDetail_Patfeelist> costlist = new ArrayList<CostDetail_Patfeelist>();

    private String admissiondate;
    //距离入院天数
    private int day = 0;

    protected View mMainView;
    protected Context mContext;
    private Act_HospitalInfo aty;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity.getApplicationContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        aty = (Act_HospitalInfo)getActivity();
        mMainView = inflater.inflate(R.layout.act_cost, container, false);
        ButterKnife.bind(this, mMainView);
        return mMainView;
    }

    @Override
    public void onStart() {
        super.onStart();
        presenter = new CostPresenter(this,new CostModel());
        Visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        admissiondate = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_DATE);
        formatter = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
        calendar.setTime(new Date());//获取当前时间
        String str = formatter.format(calendar.getTime());
        try {
            day = daysBetween(admissiondate,str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        set_time();
        showCost();
        if (SystemTool.checkNet(aty)) {
            this.dialogState(SHOW_DIALOG);
            presenter.showCostList(Visitno, calendar);
        } else {
            ViewInject.toast("网络异常，请检查网络是否连接!");
            log.error(CreateJson.LOG_JSON("", "1", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_DEPTNO), ""));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void set_time() {
        String str = formatter.format(calendar.getTime());
        cost_data.setText(str);
        cost_todaycost.setText("计费日期:" + str);
    }

    @Override
    public void showCostList(ArrayList<CostDetail_Patfeelist> list) {
        costlist = list;
        adapter = new CostListAdapter(aty, costlist);
        cost_list.setAdapter(adapter);
    }

    @Override
    public void showCostToday(String today) {
        cost_cost.setText(today);
    }

    private void showCost()
    {
        cost_totalcost.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, "patienttotal"));
        cost_prepaid.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, "patientpre"));
    }

    @OnClick(R.id.cost_left)
    public void click_left() {
        if(day > 0) {
            if (!ProUtil.isFastClick()) {
                choseCostDay(DECREASE_COST_DAY);
            }
        }
    }

    @OnClick(R.id.cost_right)
    public void click_right() {
        if (countday > 0) {
            if (!ProUtil.isFastClick()) {
                choseCostDay(INCREASE_COST_DAY);
            }
        }
    }

    public void choseCostDay(int choose){
        if (SystemTool.checkNet(aty)) {
            cost_cost.setText("");
            this.dialogState(SHOW_DIALOG);
            calendar.add(Calendar.DATE, choose);
            set_time();
            countday = countday-choose;
            day = day+choose;
            costlist.clear();
            adapter.notifyDataSetChanged();
            presenter.showCostList(Visitno, calendar);
        } else {
            ViewInject.toast("网络异常，请检查网络是否连接!");
            log.error(CreateJson.LOG_JSON("", "1", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_DEPTNO), ""));
        }
    }

    @Override
    public void dialogState(int status) {
        switch (status){
            case SHOW_DIALOG:
                dialog = new LoadingDialog(aty);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;
            case DISMISS_DIALOG:
                dialog.dismiss();
                break;
        }
    }

    /**
     *字符串的日期格式的计算
     */
    public static int daysBetween(String smdate,String bdate) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }
}
